//
//  CJBaseTableViewController.m
//  DatangLife
//
//  Created by 娜 on 2018/4/19.
//  Copyright © 2018年 DatangLife. All rights reserved.
//

#import "CJBaseTableViewController.h"

#import "CJBaseTableHeaderFooterView.h"
#import <objc/runtime.h>
#import "CJUtils.h"
#import <MJExtension.h>
const char CJBaseTableVcNavRightItemHandleKey;
const char CJBaseTableVcNavLeftItemHandleKey;

@interface CJBaseTableViewController (){
    
}
@property (nonatomic, copy) CJTableVcCellSelectedHandle handle;
@property (nonatomic, weak) UIImageView *refreshImageV;
@property (nonatomic, weak) UIView *bottomXView;
@end

@implementation CJBaseTableViewController

@synthesize needCellSepLine = _needCellSepLine;
@synthesize sepLineColor = _sepLineColor;
@synthesize navItemTitle = _navItemTitle;
@synthesize navLeftItem = _navLeftItem;
@synthesize navRightItem = _navRightItem;
@synthesize hiddenStatusBar = _hiddenStatusBar;
@synthesize barStrle = _barStrlel;



- (UIView *)bottomXView{
    if (!_bottomXView) {
        UIView *boX = [[UIView alloc] init];
        boX.backgroundColor= kWhiteColor;
        [self.view addSubview:boX];
        _bottomXView = boX;
    }
    return _bottomXView;
}

- (CJBaseTableView *)tableView{
    if (!_tableView) {
        self.bottomXView.frame = CGRectMake(0, kScreenHeight - Height_NavBar - Height_TabBar_Space, kScreenWidth, Height_TabBar_Space);
        CJBaseTableView *tabV = [[CJBaseTableView alloc] initWithFrame:CGRectMake(self.view.x, self.view.y, self.view.width, self.view.height - Height_TabBar_Space) style:UITableViewStyleGrouped];
        [self.view addSubview:tabV];
        _tableView = tabV;
        tabV.rowHeight = UITableViewAutomaticDimension;
        tabV.estimatedRowHeight = 100;
        tabV.dataSource = self;
        tabV.delegate = self;
        self.needCellSepLine = NO;
        tabV.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 0.01)];
        tabV.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 0.01)];
        if (@available(iOS 11.0, *)) {
            tabV.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        tabV.backgroundColor = [UIColor whiteColor];
        tabV.separatorColor = [UIColor colorWithHexString:kSeperatorColor];
    }
    return _tableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.page = 1;
    if ([self respondsToSelector:@selector(setEdgesForExtendedLayout:)]) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
    [NSNotificationCenter addObserver:self action:@selector(requestErroNotification) name:kCJRequestErroNotification];
    // Do any additional setup after loading the view.
}
- (void)requestErroNotification{
    [self hideLoadingAnimation];
    [self hideLoadingView];
    [self cj_endRefresh];
    [self cj_endLoadMore];
    
}
#pragma mark ============== loading & alert ==============
- (void)cj_showLoading{
    
}

- (void)cj_hiddenLoading{
    
}

- (void)cj_showTitle:(NSString *)title after:(NSTimeInterval)after{
    
}

- (void)cj_addEmptyPageWithText:(NSString *)text{
    
}

- (void)cj_setUpNavRightItemTitle:(NSString *)itemTitle handle:(void (^)(NSString *))handle{
    [self cj_setUpNavItemTitle:itemTitle handle:handle leftFlag:NO];
}

- (void)cj_setUpNavLeftItemTitle:(NSString *)itemTitle handle:(void (^)(NSString *))handle{
    [self cj_setUpNavItemTitle:itemTitle handle:handle leftFlag:YES];
}

- (void)cj_setUpNavItemTitle:(NSString *)itemTitle handle:(void (^)(NSString *itemTitle))handle leftFlag:(BOOL)leftFlag{
    if (itemTitle.length == 0 || !handle) {
        if (itemTitle == nil) {
            itemTitle = @"";
        }else if ([itemTitle isKindOfClass:[NSNull class]]){
            itemTitle = @"";
        }
        if (leftFlag) {
            self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:itemTitle style:UIBarButtonItemStylePlain target:nil action:nil];
        }else{
            self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:itemTitle style:UIBarButtonItemStylePlain target:nil action:nil];
        }
    }else{
        if (leftFlag) {
            objc_setAssociatedObject(self, &CJBaseTableVcNavLeftItemHandleKey, handle, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
            self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:itemTitle style:UIBarButtonItemStylePlain target:self action:@selector(cj_navItemHandle:)];
        } else {
            objc_setAssociatedObject(self, &CJBaseTableVcNavRightItemHandleKey, handle, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
            self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:itemTitle style:UIBarButtonItemStylePlain target:self action:@selector(cj_navItemHandle:)];
        }
    }
}


- (void)cj_navItemHandle:(UIBarButtonItem *)item{
    void (^handle)(NSString *) = objc_getAssociatedObject(self, &CJBaseTableVcNavRightItemHandleKey);
    if (handle) {
        handle(item.title);
    }
}

- (void)cj_observeNotiWithNotiName:(NSString *)notiName action:(SEL)action{
    [NSNotificationCenter addObserver:self action:action name:notiName];
}

- (void)setRefreshType:(CJBaseTableVcRefreshType)refreshType{
    _refreshType = refreshType;
    switch (refreshType) {
        case CJBaseTableVcRefreshTypeNone://没有刷新
            break;
        case CJBaseTableVcRefreshTypeOnlyCanRefresh://只有下拉刷新
        {
            [self cj_addRefresh];
        }
            break;
        case CJBaseTableVcRefreshTypeOnlyCanLoadMore://只有上拉加载
        {
            [self cj_addLoadMore];
        }
            break;
        case CJBaseTableVcRefreshTypeRefreshAndLoadMore://
        {
            [self cj_addRefresh];
            [self cj_addLoadMore];
        }
            break;
        default:
            break;
    }
}

- (void)cj_addRefresh{
    [CJUtils addPullRefreshForScrollerView:self.tableView pullRefreshCallBack:^{
        [self cj_refresh];
    }];
}

- (void)cj_addLoadMore{
    [CJUtils addLoadMoreForScrollerView:self.tableView loadMoreCallBack:^{
        [self cj_loadMore];
    }];
}

- (void)setNavItemTitle:(NSString *)navItemTitle{
    if ([navItemTitle isKindOfClass:[NSString class]] == NO) {
        return;
    }
    if ([navItemTitle isEqualToString:_navItemTitle]) {
        return;
    }
    _navItemTitle = navItemTitle.copy;
    self.navigationItem.title = navItemTitle;
}

- (NSString *)navItemTitle{
    return self.navigationItem.title;
}

- (void)setHiddenStatusBar:(BOOL)hiddenStatusBar{
    _hiddenStatusBar = hiddenStatusBar;
    [self setNeedsStatusBarAppearanceUpdate];
}

- (BOOL)hiddenStatusBar{
    return _hiddenStatusBar;
}

- (void)setBarStrle:(UIStatusBarStyle)barStrle{
    if (_barStrlel == barStrle) {
        return;
    }
    _barStrlel = barStrle;
    [self setNeedsStatusBarAppearanceUpdate];
}

- (BOOL)prefersStatusBarHidden{
    return self.hiddenStatusBar;
}

- (void)setShowRefreshIcon:(BOOL)showRefreshIcon{
    _showRefreshIcon = showRefreshIcon;
    self.refreshImageV.hidden = !showRefreshIcon;
}

- (UIImageView *)refreshImageV{
    if (!_refreshImageV) {
        UIImageView *refreshImg = [[UIImageView alloc] init];
        [self.view addSubview:refreshImg];
        _refreshImageV = refreshImg;
        [self.view bringSubviewToFront:refreshImg];
        refreshImg.image = [UIImage imageNamed:@"refresh"];
        WeakSelf(weakSelf);
        [refreshImg mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(weakSelf.view).mas_offset(-15);
            make.size.mas_equalTo(CGSizeMake(44, 44));
            make.bottom.mas_equalTo(weakSelf.view).mas_offset(-20);
        }];
        refreshImg.layerCornerRadius = 22;
        refreshImg.backgroundColor = kWhiteColor;
        [refreshImg setTapActionWithBlock:^{
            [self startAnimation];
            [weakSelf cj_beginRefresh];
        }];
    }
    return _refreshImageV;
}

- (void)startAnimation{
    CABasicAnimation *rotationAnimation;
    rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    rotationAnimation.toValue = [NSNumber numberWithFloat:M_PI *2.0];
    rotationAnimation.duration = 1.5;
    rotationAnimation.cumulative = YES;
    rotationAnimation.repeatCount = MAXFLOAT;
    [self.refreshImageV.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
}

- (void)endRefreshIconAnimation{
    [self.refreshImageV.layer removeAnimationForKey:@"rotationAnimation"];
}

- (UIStatusBarStyle)preferredStatusBarStyle{
    return self.barStrle;
}

- (void)setNavRightItem:(UIBarButtonItem *)navRightItem{
    _navRightItem = navRightItem;
    self.navigationItem.rightBarButtonItem = navRightItem;
}

- (UIBarButtonItem *)navRightItem{
    return self.navigationItem.rightBarButtonItem;
}

- (void)setNavLeftItem:(UIBarButtonItem *)navLeftItem{
    _navLeftItem = navLeftItem;
    self.navigationItem.leftBarButtonItem = navLeftItem;
}

- (UIBarButtonItem *)navLeftItem{
    return self.navigationItem.leftBarButtonItem;
}

- (void)setNeedCellSepLine:(BOOL)needCellSepLine{
    _needCellSepLine = needCellSepLine;
    self.tableView.separatorStyle = needCellSepLine ? UITableViewCellSeparatorStyleSingleLine : UITableViewCellSeparatorStyleNone;
}

- (BOOL)needCellSepLine{
    return self.tableView.separatorStyle == UITableViewCellSeparatorStyleSingleLine;
}

- (void)setTableEdgeInset:(UIEdgeInsets)tableEdgeInset{
    _tableEdgeInset = tableEdgeInset;
    [self.view setNeedsUpdateConstraints];
    [self.view updateConstraintsIfNeeded];
    [self.view layoutIfNeeded];
    [self.view setNeedsLayout];
}

- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    self.tableView.frame = self.view.bounds;
    [self.view sendSubviewToBack:self.tableView];
}

- (void)setSepLineColor:(UIColor *)sepLineColor{
    if (!self.needCellSepLine) {
        return;
    }
    _sepLineColor = sepLineColor;
    if (sepLineColor) {
        self.tableView.separatorColor = sepLineColor;
    }
}

- (UIColor *)sepLineColor{
    return _sepLineColor ? _sepLineColor : [UIColor whiteColor];
}

- (void)cj_reloadData{
    [self.tableView reloadData];
}

- (void)cj_beginRefresh{
    if (self.refreshType == CJBaseTableVcRefreshTypeOnlyCanRefresh || self.refreshType == CJBaseTableVcRefreshTypeRefreshAndLoadMore) {
        [CJUtils beginPullRefreshForScrollView:self.tableView];
    }
}

- (void)cj_refresh{
    self.page = 1;
    if (self.refreshType == CJBaseTableVcRefreshTypeNone || self.refreshType == CJBaseTableVcRefreshTypeOnlyCanLoadMore) {
        return;
    }
    self.isRefresh = YES;
    self.isLoadMore = NO;
}

- (void)cj_loadMore{
    self.page ++;
    if (self.refreshType == CJBaseTableVcRefreshTypeNone || self.refreshType == CJBaseTableVcRefreshTypeOnlyCanRefresh) {
        return;
    }
    if (self.dataArray.count == 0) {
        self.page = self.page-1;
        return;
    }
    self.isRefresh = NO;
    self.isLoadMore = YES;
}

//- (void)cj_commonConfigResponseWithPesponse:(id)response isRefresh:(BOOL)isRefresh modelClass:(__unsafe_unretained Class)modelClass{
//    [self cj_commonConfigResponseWithResponse:response isRefresh:isRefresh modelClass:modelClass emptyText:nil];
//}
//
//- (void)cj_commonConfigResponseWithResponse:(id)response isRefresh:(BOOL)isRefresh modelClass:(__unsafe_unretained Class)modelClass emptyText:(NSString *)emptyText{
//    if ([response isKindOfClass:[NSArray class]] == NO) {
//        return;
//    }
//    if (self.isRefresh) {
//        [self cj_endRefresh];
//
//         // 设置模型数组
//        [self.dataArray removeAllObjects];
//        self.dataArray = [modelClass mj_objectWithKeyValues:response];
//
//        // 设置空界面占位文字
//        if (emptyText.length) {
//            [self cj_addEmptyPageWithText:emptyText];
//        }
//        [self cj_reloadData];
//    }else{
//        //停止上拉
//        [self cj_endLoadMore];
//        if ([response count] == 0) {
//            [self cj_noticeNoMoreData];
//        }else{
//            //设置模型数组
//            NSArray *newModels = [modelClass mj_objectArrayWithKeyValuesArray:response];
//            if (newModels.count < 50) {
//                [self cj_hiddenLoadMore];
//            }
//            [self.dataArray addObjectsFromArray:newModels];
//
//           [self cj_reloadData];
//
//        }
//    }
//}

- (void)cj_endRefresh{
    if (self.refreshType == CJBaseTableVcRefreshTypeOnlyCanRefresh || self.refreshType == CJBaseTableVcRefreshTypeRefreshAndLoadMore) {
        [CJUtils endRefreshForScrollerView:self.tableView];
    }
}

- (void)cj_endLoadMore{
    if (self.refreshType == CJBaseTableVcRefreshTypeOnlyCanLoadMore || self.refreshType == CJBaseTableVcRefreshTypeRefreshAndLoadMore) {
//        [self cj_hiddenLoadMore];
        [CJUtils endLoadMoreForScrollerView:self.tableView];
    }
}

- (void)cj_hiddenRefresh{
    if (self.refreshType == CJBaseTableVcRefreshTypeOnlyCanRefresh || self.refreshType == CJBaseTableVcRefreshTypeRefreshAndLoadMore) {
        [CJUtils hiddenHeaderForScrollerView:self.tableView];
    }
}

- (void)cj_hiddenLoadMore{
    if (self.refreshType == CJBaseTableVcRefreshTypeOnlyCanLoadMore || self.refreshType == CJBaseTableVcRefreshTypeRefreshAndLoadMore) {
        [CJUtils hiddenFooterForScrollerView:self.tableView];
    }
}

- (void)cj_noticeNoMoreData{
    if (self.refreshType == CJBaseTableVcRefreshTypeOnlyCanLoadMore || self.refreshType == CJBaseTableVcRefreshTypeRefreshAndLoadMore) {
        [CJUtils noticeNoMoreDataForScrollerView:self.tableView];
    }
}

- (BOOL)isHeaderRefreshing{
    return [CJUtils headerIsRefreshForScrollerView:self.tableView];
}

- (BOOL)isFooterRefreshing{
    return [CJUtils footerIsRefreshForScrollerView:self.tableView];
}

#pragma mark ============== UITableViewDelegate &  UITableViewDataSource==============

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if ([self respondsToSelector:@selector(cj_numberOfSections)]) {
        if (self.isSuccessNet) {
            return self.cj_numberOfSections;
        }else{
            return 0;
        }
        
    }
    return 0;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if ([self respondsToSelector:@selector(cj_numberOfRowsInsection:)]) {
        
        if (self.isSuccessNet) {
            return [self cj_numberOfRowsInsection:section];
        }else{
            return 0;
        }
    }
    return 0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if ([self respondsToSelector:@selector(cj_headerAtSection:)]) {
        
        if (self.isSuccessNet) {
            return [self cj_headerAtSection:section];
        }else{
            return 0;
        }
    }
    return nil;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    if ([self respondsToSelector:@selector(cj_footerAtSection:)]) {
        
        if (self.isSuccessNet) {
            return [self cj_footerAtSection:section];
        }else{
            return 0;
        }
    }
    return nil;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([self respondsToSelector:@selector(cj_cellAtIndexPath:)]) {
        return [self cj_cellAtIndexPath:indexPath];
    }
    CJBaseTableViewCell *cell = [CJBaseTableViewCell cellWithTableView:self.tableView];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    CJBaseTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if ([self respondsToSelector:@selector(cj_didSelectCellAtIndexPath:cell:)]) {
        [self cj_didSelectCellAtIndexPath:indexPath cell:cell];
    }
}

// 设置分割线偏移间距并适配
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (!self.needCellSepLine) return ;
    UIEdgeInsets edgeInsets = UIEdgeInsetsMake(0, 15, 0, 0);
    if ([self respondsToSelector:@selector(cj_sepEdgeInsetsAtIndexPath:)]) {
        edgeInsets = [self cj_sepEdgeInsetsAtIndexPath:indexPath];
    }
    if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) [tableView setSeparatorInset:edgeInsets];
    if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) [tableView setLayoutMargins:edgeInsets];
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) [cell setSeparatorInset:edgeInsets];
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) [cell setLayoutMargins:edgeInsets];
}

// 每一行的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([self respondsToSelector:@selector(cj_cellHeightAtIndexPath:)]) {
        
        if (self.isSuccessNet) {
            return [self cj_cellHeightAtIndexPath:indexPath];
        }else{
            return 0;
        }
    }
    return tableView.rowHeight;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if ([self respondsToSelector:@selector(cj_sectionHeaderHeightAtSection:)]) {
        
        if (self.isSuccessNet) {
            return [self cj_sectionHeaderHeightAtSection:section];
        }else{
            return 0.01;
        }
    }
    return 0.01;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if ([self respondsToSelector:@selector(cj_sectionFooterHeightAtSection:)]) {
        
        if (self.isSuccessNet) {
            return [self cj_sectionFooterHeightAtSection:section];
        }else{
            return 0.01;
        }
    }
    return 0.01;
}

- (NSInteger)cj_numberOfSections{
    return 0;
}

- (NSInteger)cj_numberOfRowsInsection:(NSInteger)section{
    return 0;
}

- (CJBaseTableViewCell *)cj_cellAtIndexPath:(NSIndexPath *)indexPath{
    return [CJBaseTableViewCell cellWithTableView:self.tableView];
}

- (CGFloat)cj_cellHeightAtIndexPath:(NSIndexPath *)indexPath{
    return 0;
}

- (void)cj_didSelectCellAtIndexPath:(NSIndexPath *)indexPath cell:(CJBaseTableViewCell *)cell{
    
}

- (UIView *)cj_headerAtSection:(NSInteger)section{
    return [CJBaseTableHeaderFooterView headerFooterViewWithTableView:self.tableView];
}

- (UIView *)cj_footerAtSection:(NSInteger)section{
    return [CJBaseTableHeaderFooterView headerFooterViewWithTableView:self.tableView];
}

- (CGFloat)cj_sectionHeaderHeightAtSection:(NSInteger)section{
    return 0.01;
}

-(CGFloat)cj_sectionFooterHeightAtSection:(NSInteger)section{
    return 0.01;
}

- (UIEdgeInsets)cj_sepEdgeInsetsAtIndexPath:(NSIndexPath *)indexPath{
    return UIEdgeInsetsMake(0, 15, 0, 0);
}

- (void)dealloc{
    [NSNotificationCenter removeAllObserverForObj:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
